<template>
  <div>
    <el-dialog v-el-drag-dialog title="Topic Fragment" width="60%" :visible.sync="dialogVisible">
      <el-form ref="dataForm" :rules="rules" :model="form">
        <el-form-item prop="content">
          <el-input v-model="form.content" :autosize="{ minRows: 6, maxRows: 10 }" type="textarea" placeholder="support markdown" />
        </el-form-item>
        <el-form-item>
          <el-button v-loading="loading" style="float: right;" type="primary" @click="submitForm">Confirm</el-button>
          <el-button v-loading="loading" style="float: right;margin-right: 10px;" @click="dialogVisible = false">Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import { updateTopicSnippet } from '@/api/info/topic-snippet'

export default {
  name: 'EditSnippet',
  directives: { elDragDialog },
  data() {
    return {
      form: {},
      rules: {
        content: [{ required: true, message: ' ', trigger: 'blur' }]
      },
      dialogVisible: false,
      loading: false
    }
  },
  watch: {
    form: {
      handler: function(newVal, oldVal) {
        const k = 'snippet' + this.form.id
        sessionStorage.setItem(k, JSON.stringify(newVal))
      },
      deep: true
    }
  },
  created() {
    this.$on('open', function(row) {
      this.dialogVisible = true
      // 实现再次打开扔保留未保存内容
      let content = row.content
      const cache = sessionStorage.getItem('snippet' + row.id)
      if (cache) {
        content = JSON.parse(cache).content
      }
      this.form = Object.assign({}, row, { content: content }, { createAt: undefined, modifyAt: undefined })
    })
  },
  methods: {
    submitForm() {
      console.log(this.form)
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          updateTopicSnippet(this.form)
            .then(response => {
              // 向父组件返回数据
              this.$emit('editcb', response.result)
              this.$notify({
                title: 'Success',
                message: 'save successfully',
                type: 'success',
                duration: 2000
              })
              this.dialogVisible = false
            })
            .catch(() => {
              this.loading = false
            })
          this.loading = false
        }
      })
    }
  }
}
</script>
